package pswvclass.pswvandroid2.com;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.EnvUtils;
import com.alipay.sdk.app.PayTask;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.util.HttpUtils;
import pswvclass.pswvandroid2.com.util.payment.AuthResult;
import pswvclass.pswvandroid2.com.util.payment.H5PayDemoActivity;
import pswvclass.pswvandroid2.com.util.payment.OrderInfoUtil2_0;
import pswvclass.pswvandroid2.com.util.payment.PayResult;

/**
 */
public class Payment extends AppCompatActivity implements View.OnClickListener {

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016092400586693";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088102177083038";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "0.1";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCjpZpVulkYyIOX\n" +
            "HloS/hCGnLnz/w6W3an7rJ1Hb3hP19ksFCP7wEYO0QLYYF4s6clIlMoi/wZE/V8u\n" +
            "NB1QeGr4aPBQvlj9PNrTvJd028QbZjJZ15bJqIDrjLXoG3i1dahufUqEf8rhdBeb\n" +
            "1yTfiIL6glAAWpBjROD7A29AcoWVRNiQFO51vQ6CxhlLmdWnegAEOC4FYQ6+hXf9\n" +
            "5vJnYmvoTdAoufXjG3H3BWRufjEl0JuojvO+oVkLQ7tMh9dWiUAN/F6AnB/UC7RX\n" +
            "d4/l0dVaWyaTmKQIdNkogxI/h5wH+UE9QiVeNGEjEt1CWMyW1wbx85RjG6iH9V6F\n" +
            "w07xUSezAgMBAAECggEAJPSw9csvc7lUfjwMe12EveGG3OMsmEVWrc89dXRm5yEH\n" +
            "mjyyI5g4OgBZdCPPILVrD0kKnPyandnaNMTwGcwX3CFWo+VYk1e60zYzveAjWUyq\n" +
            "8j8NflzfQFJ2ggQyLkhz0P/aZDG3z1I4QqlDWnepnIjxKCNLmB9l70nHRfaW1C5r\n" +
            "XQMBdlI4ng+JYVfGO8zLfutuTvpG5WU+JAM+rKBZkrdOw8Vd4qkctddgDsz4o6W9\n" +
            "X7FpsrbludjQlB/dLfS+1By1eP6cUEh4toYw0CX///1XUZ5Nrzaz/yfm5LXJ0kas\n" +
            "pmTGuaUABXNIKFvqGDpW4nCUeBEbtcBgY9LX14TfAQKBgQDZVDpEbYwXC5DCoTYS\n" +
            "4LA+fRCivjgi0y1ocwB9nJ1IGlnYmbjs0ME5GwLtd8DcQ4pOFK4QhtjG7iMl4VkS\n" +
            "ZdJfNQLAkJ8C7XJZvq7Ic4Pgu7+3rXw7VRB957rvmB6z+Xt8H0iCF3aJwX8LLRfz\n" +
            "tQapMZmy5sKpir/kWq5bFXDNeQKBgQDAxAv0Cp5NzxNyDJ5NXqzY2YIXaeH4YQhL\n" +
            "KXU3WrNR+EgTUcTzWIcRTSHptgemhDSSrEEJVsUair+J2Qwm8ywAhXjCXuXGBK7J\n" +
            "CkYF4kXtUf3VCkTT2TtXRvD9oIxbUx5Ot0YSj1NmSJy33dTen1DL9M5GoQ9QPKdl\n" +
            "D+dc2OOPiwKBgQCyGWdCqm+SdyTjiw9wOvfTzdPzOmVwjJT6srvlNJJkA0w7yAYW\n" +
            "9CBUtwEYL/o5x5Ow1xuqaYd+xqrBIUJIZG8ZHK0rt5jH4mTCjRRZKukZI2NCmAZl\n" +
            "7Rj9xQiZzpTisoHyvwRBsA6xZ4PAWez2CBT0VLR7OsauAAmvjmyyMgjmKQKBgQCI\n" +
            "t0LHDfTiuJhRDjQEKb6refCzTGxxLdik/j1dSh3eaBouYZMvCD2bfroruOfKKP/k\n" +
            "evkRd5IJ1hgs21ysD1HI+OEB8i5C+DVC7t9k8uunerxtqX/RRMO6jd0D9Sc26keX\n" +
            "ipLPPQnohF1qZpHAZvv1+6WFIFvtC2ep3NK53jXfKwKBgQC4RBSyrMKuxWRq2mpT\n" +
            "kpQR5Bme0PYqNKJoM2Qqx/IXwi1yv9U0WVsluhy7mx/+EeIx+ITzIW4zOnOl5FP3\n" +
            "9NQyu0mZ5mRvlHlc8BZ11qhBGpXeDtijkk+wuzEEancvmiTM6cCGmlkgi1vUjigE\n" +
            "y4FeecZ9HfAkm1ZA3Oqy09V+Wg==";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 0;
    private static final int SDK_AUTH_FLAG = 1;
    private String tag = "Login";
    private Button zhifu;
    private Button zhifusq;
    private Button zhifuym;

    @Override
    protected void onCreate(Bundle bundle) {
        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(bundle);
        setContentView(R.layout.payment);
        zhifu = (Button) findViewById(R.id.zhifu);
        zhifu.setOnClickListener(this);
        zhifusq = (Button) findViewById(R.id.zhifusq);
        zhifusq.setOnClickListener(this);
        zhifuym = (Button) findViewById(R.id.zhifuym);
        zhifuym.setOnClickListener(this);
    }


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case SDK_PAY_FLAG:
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        Toast.makeText(Payment.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(Payment.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;

                case SDK_AUTH_FLAG:
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus1 = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus1, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(Payment.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(Payment.this,
                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();


                        break;
                    }
                default:
                    break;
            }

        }

        ;

    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.zhifuym:
                Intent intent2 = new Intent(Payment.this, H5PayDemoActivity.class);
                Bundle extras = new Bundle();
                /**
                 * url 是要测试的网站，在 Demo App 中会使用 H5PayDemoActivity 内的 WebView 打开。
                 *
                 * 可以填写任一支持支付宝支付的网站（如淘宝或一号店），在网站中下订单并唤起支付宝；
                 * 或者直接填写由支付宝文档提供的“网站 Demo”生成的订单地址
                 * （如 https://mclient.alipay.com/h5Continue.htm?h5_route_token=303ff0894cd4dccf591b089761dexxxx）
                 * 进行测试。
                 *
                 * H5PayDemoActivity 中的 MyWebViewClient.shouldOverrideUrlLoading() 实现了拦截 URL 唤起支付宝，
                 * 可以参考它实现自定义的 URL 拦截逻辑。
                 */
                String url = "http://m.taobao.com";
                extras.putString("url", url);
                intent2.putExtras(extras);
                startActivity(intent2);
                break;
            case R.id.zhifusq:
                if (TextUtils.isEmpty(PID) || TextUtils.isEmpty(APPID)
                        || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))
                        || TextUtils.isEmpty(TARGET_ID)) {
                    new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置PARTNER |APP_ID| RSA_PRIVATE| TARGET_ID")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialoginterface, int i) {
                                }
                            }).show();
                    return;
                }

                /**
                 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
                 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
                 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
                 *
                 * authInfo的获取必须来自服务端；
                 */
                boolean rsa2 = (RSA2_PRIVATE.length() > 0);
                Map<String, String> authInfoMap = OrderInfoUtil2_0.buildAuthInfoMap(PID, APPID, TARGET_ID, rsa2);
                String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);

                String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
                String sign = OrderInfoUtil2_0.getSign(authInfoMap, privateKey, rsa2);
                final String authInfo = info + "&" + sign;
                Runnable authRunnable = new Runnable() {

                    @Override
                    public void run() {
                        // 构造AuthTask 对象
                        AuthTask authTask = new AuthTask(Payment.this);
                        // 调用授权接口，获取授权结果
                        Map<String, String> result = authTask.authV2(authInfo, true);

                        Message msg = new Message();
                        msg.what = SDK_AUTH_FLAG;
                        msg.obj = result;
                        Log.v(tag, result + "");
                        mHandler.sendMessage(msg);
                    }
                };

                // 必须异步调用
                Thread authThread = new Thread(authRunnable);
                authThread.start();

                break;

            case R.id.zhifu:

                if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
                    new AlertDialog.Builder(this).setTitle("警告").setMessage("需要配置APPID | RSA_PRIVATE")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialoginterface, int i) {
                                    //
                                    finish();
                                }
                            }).show();
                    return;
                }

                /**
                 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
                 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
                 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
                 *
                 * orderInfo的获取必须来自服务端；
                 */
                boolean rsa21 = (RSA2_PRIVATE.length() > 0);
                Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa21);
                String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
                Log.v(tag, orderParam + "           =========");
                String privateKey1 = rsa21 ? RSA2_PRIVATE : RSA_PRIVATE;
                String sign1 = OrderInfoUtil2_0.getSign(params, privateKey1, rsa21);
                final String orderInfo = orderParam + "&" + "total_fee=0.01&" + sign1;
                Log.v(tag, orderInfo);
                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(Payment.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        Log.i("msp", result.toString());
                        Log.v(tag, result + "");
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
                break;
            default:
                break;
        }
    }
}
